#include "ini_parser.h"


int INIParser::parser(){

	FILE* fp = fopen(inifile, "r");
	if(NULL == fp){

		return -1; 
	}   

	std::string SECTION("");
	while(!feof(fp)){

		char _buf[MAX_BUF_SIZE] = {
			0};
		char* gret = fgets(_buf, MAX_BUF_SIZE, fp);
		if(NULL == gret){

			continue;
		}   
		std::string sbuf(_buf);
		sbuf.erase(0, sbuf.find_first_not_of(" "));
		sbuf.erase(sbuf.find_last_not_of(" ")+1);

		//skip comments
		if(comments.end() != find(comments.begin(), comments.end(), sbuf[0])){

			continue;
		}   

		if('[' == sbuf[0]){

			sbuf.erase(0, sbuf.find_first_not_of("["));
			sbuf.erase(sbuf.find_last_not_of("]")-1);
			SECTION = sbuf;

		}else{

			size_t pos = sbuf.find("=");
			if(std::string::npos == pos){

				continue;
			}   

			std::string key = sbuf.substr(0, pos);
			std::string value = sbuf.substr(pos+1);
			value.erase(value.find_last_not_of("\r\n")+1);
			inimap[SECTION][key] = value;
		}   
	}   

	fclose(fp);

	return 0;
}

ssmap& INIParser::getKeyValBySection(const char* section){

	return inimap[std::string(section)];
}

